package com.blockserverclient;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

import static com.TestByteBuffer.transferDataFromChannelToChannel;

/**
 * @author 罗俊华
 * @date 2021/8/18 - 5:30 下午
 */
@Slf4j
public class Client {

    public static void main(String[] args) throws IOException {
        try (SocketChannel socketChannel = SocketChannel.open()) {

            boolean connected = socketChannel.connect(new InetSocketAddress("localhost", 2356));

            if (connected) {
                log.info("connected to server...");
                ByteBuffer requestBuffer = StandardCharsets.UTF_8.encode("hello,server,form client...");

                log.info("prepare to send request to server...");
                try(FileChannel fromChannel = new FileInputStream("/Users/luo/temp/nacos-server-1.4.1.tar.gz").getChannel();){

                    transferDataFromChannelToChannel(fromChannel, socketChannel,  1024*1024);
                }
                /*while (requestBuffer.hasRemaining()){
                    socketChannel.write(requestBuffer);
                }*/

                ByteBuffer respBuffer = ByteBuffer.allocate(32);

                log.info("waiting for server's response");
                int read = socketChannel.read(respBuffer);

                log.info("received {} byte data", read);
                respBuffer.flip();
                while (respBuffer.hasRemaining()) {
                    System.out.println(StandardCharsets.UTF_8.decode(respBuffer).toString());
                }
                log.info("close connection");
            }
        }
    }
}
